package cn.caplike.demo.nio._2017;

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 简介：MappedByteBuffer
 *
 * @author 李珂 2017年11月24日 下午1:41:35
 */
public class MappedByteBufferTest01 {

	public static void main(String[] args) throws IOException {
		int length = 0x8FFFFFF; // 一个byte占1B，所以共向文件中存128M的数据
		try (FileChannel channel = FileChannel.open(Paths.get("data/mappedbytebuffer/target.txt"),
				StandardOpenOption.DELETE_ON_CLOSE,
				StandardOpenOption.WRITE,
				StandardOpenOption.READ)) {
			MappedByteBuffer mapBuffer = channel.map(MapMode.READ_WRITE, 0, length);

			for (int i = 0; i < length; i++) {
				mapBuffer.put((byte) 0);
			}

			for (int i = length / 2; i < length / 2 + 4; i++) {
				System.out.println(mapBuffer.get(i));
			}

		}
		System.exit(0);
	}

}
